﻿using Minecraft.BLL.mysql;
using Minecraft.Config;
using Minecraft.Model;
using Minecraft.Model.Backpack;
using Minecraft.Model.ReqResp;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Minecraft.ServerHall.Cmd
{
	public class BackpackGoodsSplit : CommandBase<MinecraftSession, StringRequestInfo>
	{
		public override string Name
		{
			get
			{
				return ProtocolHelper.GetProtocolStr(defCommand);
			}
		}
		private EnumCommand defCommand = EnumCommand.Backpack_BackpackGoodsSplit;
		public override void ExecuteCommand(MinecraftSession session, StringRequestInfo requestInfo)
		{
			var req = requestInfo.GetRequestObj<BackpackGoodsSplitReq>(session);
			if (req == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：请求实体为空）" });
				return;
			}
			if (!session.minecraftSessionInfo.IsLogin)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：未登录）" });
				return;
			}

			//if (JsonConfig.Value.IsDebug)
			//{
			//	for (int i = 0; i < 10; i++)
			//	{
			//		session.minecraftSessionInfo.goodsList.Add(new GoodsModel
			//		{
			//			 BelongsTo=(int)EnumGoodsBelongsToType.FurnitureStorage,
			//			  GoodsId = StringHelper.GetGuidStr(),
			//			   GoodsItemId = "100001",
			//			    GoodsPosition = 4,
			//				 guid= session.minecraftSessionInfo.furnitureStorageList.FirstOrDefault().FurnitureId,
			//				  PlayerId =session.minecraftSessionInfo.player.PlayerId,
			//				   WastageValue = 100

			//		});
			//	}
			//	req = new BackpackGoodsSplitReq
			//	{
			//		 enumGoodsBelongsToType= EnumGoodsBelongsToType.FurnitureStorage,
			//		  SplitNumOfNewPosition  =5,
			//		   GoodsPosition = 4,
			//		    guid = session.minecraftSessionInfo.furnitureStorageList.FirstOrDefault().FurnitureId
			//			,
			//	};
			//}

			//物品来源判断
			if (!MinecraftConfig.enumGoodsSourceBelongsToTypeList.Any(m => m == req.enumGoodsBelongsToType))
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：物品来源不正确，前端传入的物品来源为【{req.enumGoodsBelongsToType.ToString()}】）" });
				return;
			}
			if (req.GoodsPosition < 0)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误2（原因：GoodsPosition < 0）" });
				return;
			}
			if (req.SplitNumOfNewPosition <= 0)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误3（原因：SplitNumOfNewPosition <= 0）" });
				return;
			}
			if (req.guid.IsNullOrWhiteSpace())
			{
				req.guid = "";
			}
			var baseResp = req.enumGoodsBelongsToType.GetBackpackGoodsBelongsToTypeBaseType(req.GoodsPosition, session, "BackpackGoodsSplit", req.guid);
			if (baseResp.RespLevel != RespLevelEnum.Success)
			{
				session.Send(defCommand, req, baseResp);
				return;
			}

			//进一步判断当前type的position的goodsList的合法性
			Func<GoodsModel, bool> predicateW = m =>
				m.enumGoodsBelongsToType_Convert == req.enumGoodsBelongsToType && m.GoodsPosition == req.GoodsPosition && m.Num > 0 && m.guid == req.guid;
			//得到当前位置的物品信息列表
			var curGoodsIdInfo = session.minecraftSessionInfo.goodsList.FirstOrDefault(predicateW);
			if (curGoodsIdInfo == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误7（原因：指定格子中的物品不存在）" });
				return;
			}
			if (req.SplitNumOfNewPosition >= curGoodsIdInfo.Num)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误8（原因：SplitNumOfNewPosition 参数 大于等于当前位置的物品个数）" });
				return;
			}
			//如果对快捷栏拆分，则优先存放快捷栏，快捷栏满了，则存背包，如果背包满了，则拆分失败
			//如果对背包拆分，则只对背包操作，如果背包满了，则拆分失败


			//加载背包物品goodsItem信息
			List<BackpackGoodsItemInfo> goodsItemInfoList = session.GetBackpackGoodsItemInfoList(req.enumGoodsBelongsToType, req.guid, out BaseResp baseResp2);
			if (baseResp2.RespLevel != RespLevelEnum.Success)
			{
				session.Send(defCommand, req, baseResp2);
				return;
			}

			var curGoodsItemInfo = goodsItemInfoList.FirstOrDefault(m => m.enumGoodsBelongsToType == req.enumGoodsBelongsToType && m.GoodsPosition == req.GoodsPosition && m.guid == req.guid);
			if (curGoodsItemInfo == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误9（原因：服务器错误，占位组装模拟物品位置信息失败，最可能的原因时是服务器代码中判断位置方法出错，或者guid不为空时，对应的信息不存在）" });
				return;
			}
			//从配置中读取指定物品存放数量上限
			//var goodsItemMaxNum = session.GetMaxCellNumConvert(curGoodsItemItemInfo.GoodsItemId);

			//找到能够满足存放物品条件的位置信息
			Func<BackpackGoodsItemInfo, bool> predicateWhere = m => m.GoodsNum <= 0;
			var goodsItemInfo = goodsItemInfoList.FirstOrDefault(predicateWhere);
			if (goodsItemInfo == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误10（原因：格子已经满了，无法存放新拆分的物品，拆分失败）" });
				return;
			}

			////拆分操作，更新缓存
			////得到被拆分出来的splitGoodsList
			//var splitGoodsList = curGoodsIdInfo.Take(req.SplitNumOfNewPosition).ToList();

			//splitGoodsList.ForEach(item =>
			//{
			//	var itemCopy = item.DeepCopy();
			//	session.minecraftSessionInfo.goodsList.RemoveAll(m => m.GoodsId == itemCopy.GoodsId);
			//	itemCopy.BelongsTo = (int)goodsItemInfo.enumGoodsBelongsToType;
			//	itemCopy.GoodsPosition = goodsItemInfo.GoodsPosition;
			//	session.minecraftSessionInfo.goodsList.Add(itemCopy);
			//});

			curGoodsIdInfo.Num -= req.SplitNumOfNewPosition;
			var splitInfo = new GoodsModel
			{
				BelongsTo = (int)goodsItemInfo.enumGoodsBelongsToType,
				GoodsId = StringHelper.GetGuidStr(),
				GoodsItemId = curGoodsIdInfo.GoodsItemId,
				GoodsPosition = goodsItemInfo.GoodsPosition,
				guid = curGoodsIdInfo.guid,
				Num = req.SplitNumOfNewPosition,
				PlayerId = session.minecraftSessionInfo.player.PlayerId,
				WastageValue = 100
			};
			session.minecraftSessionInfo.goodsList.Add(splitInfo);

			//添加操作影响的positionOptList
			List<BackpackGoodsPositionOpt> positionOptList = new List<BackpackGoodsPositionOpt>();
			positionOptList.Add(new BackpackGoodsPositionOpt
			{
				enumGoodsBelongsToType = curGoodsIdInfo.enumGoodsBelongsToType_Convert,
				GoodsPosition = curGoodsIdInfo.GoodsPosition,
				guid = curGoodsIdInfo.guid,
			});
			positionOptList.Add(new BackpackGoodsPositionOpt
			{
				enumGoodsBelongsToType = goodsItemInfo.enumGoodsBelongsToType,
				GoodsPosition = goodsItemInfo.GoodsPosition,
				guid = goodsItemInfo.guid,
			});

			////过滤goods position操作条件
			//Func<BackpackGoodsPositionOpt, bool> predicateGoodsPositionOpt = m =>
			//	m.enumGoodsBelongsToType == goodsItemInfo.enumGoodsBelongsToType && m.GoodsPosition == goodsItemInfo.GoodsPosition && m.guid == req.guid;
			//if (!positionOptList.Any(predicateGoodsPositionOpt))
			//{
			//	positionOptList.Add(new BackpackGoodsPositionOpt
			//	{
			//		enumGoodsBelongsToType = goodsItemInfo.enumGoodsBelongsToType,
			//		GoodsPosition = goodsItemInfo.GoodsPosition,
			//		guid = req.guid,
			//	});
			//}

			//获取响应数据
			//找到受影响的物品位置信息
			Func<GoodsModel, bool> predicateBeAffected = m =>
				positionOptList.Any(n => n.enumGoodsBelongsToType == m.enumGoodsBelongsToType_Convert
				&& n.GoodsPosition == m.GoodsPosition && m.guid == req.guid);
			var posGoodsinfoList = session.minecraftSessionInfo.goodsList.Where(predicateBeAffected).GetBackpackGoodsCellInfo();

			//响应数据：返回受拆分影响的物品位置信息列表
			var resp = new BackpackGoodsSplitResp
			{
				backpackShortcutBarCellInfoList = posGoodsinfoList,
				enumGoodsBelongsToType = req.enumGoodsBelongsToType,
				guid = req.guid
			};
			session.Send(defCommand, req, resp);
		}
	}
}
